/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.generators.reports.generators;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;

import org.bugstat.common.bugs.Bug;
import org.bugstat.common.bugs.User;
import org.bugstat.generators.CanGenerateReports;
import org.bugstat.generators.GeneratorsStrings;
import org.bugstat.generators.reports.PerPersonReportGeneratorBase;
import org.bugstat.generators.reports.TimedIntegerReport;

/**
 * This class generates a time that takes a person to fix a bug (or assign it to a different person)
 *
 * @author Basil Shikin
 */
@CanGenerateReports
public class OpenBugsAgePerPerson
    extends PerPersonReportGeneratorBase<TimedIntegerReport>
{
    private final Map<User, Collection<Integer>> currentlyClosedBugs = new HashMap<User, Collection<Integer>>( 150 );    
    private final Map<User, Map<Integer, Integer>> bugOpenDuration = new HashMap<User, Map<Integer, Integer>>(); // Bug ID -> Number of days open
    private final Map<Integer, User> currentAssignees = new HashMap<Integer, User>();
    
    public OpenBugsAgePerPerson()
    {
        setName( GeneratorsStrings.TEXT_TIME_TO_FIX_PER_PERSON );
        setValueThreshold( 7 ); // Do not show anyone who has maximum resolution time in a week
    }
    
    @Override
    public void periodStarted(Date startDate)
    {
        super.periodStarted( startDate );
        
        currentlyClosedBugs.clear();
    }

    @Override
    public void periodEnded()
    {
        super.periodEnded();
                
        // First, calculate average bug age for all people
        for ( Entry<User, Map<Integer,Integer>> entry: bugOpenDuration.entrySet() )
        {
            final User user = entry.getKey();
            final TimedIntegerReport report = retrieveReport( user );
            
            float averageBugAge = 0;
            for ( Integer bugAge : entry.getValue().values() )
            {
                averageBugAge += bugAge;
            }
            averageBugAge = averageBugAge / entry.getValue().size();
            
            report.putValue( currentDate, OpenBugsAge.normalizeBugAge( averageBugAge, currentInterval ) );
        }
        
        // Second, remove all fixed bugs from open bugs list
        for ( Entry<User, Collection<Integer>> entry : currentlyClosedBugs.entrySet() )
        {
            final User user = entry.getKey();
            final Map<Integer, Integer> openBugs = bugOpenDuration.get( user );
            
            if ( openBugs != null )
            {
                for ( Integer bugID : entry.getValue() )
                {
                    openBugs.remove( bugID );
                }
            }
        }
    }

    @Override
    public void processBug(Bug bug)
    {
        if ( !bug.isEnhancement() )
        {
            final int bugID = bug.getId();
            
            User lastKnownAssignee = currentAssignees.get( bugID );
            if ( lastKnownAssignee == null )
            {
                lastKnownAssignee = bug.getAssignedTo();
            }
            else if ( !bug.getAssignedTo().equals( lastKnownAssignee ) )
            {
                markBugClosed( lastKnownAssignee, bugID );
            }
            
        
            if ( bug.isOpen() )
            {
                increaseDaysOpen( bug.getAssignedTo(), bugID );               
            }
            else
            {
                markBugClosed( bug.getAssignedTo(), bugID );
            }
        }
    }

    private void increaseDaysOpen(User assignee, int bugID)
    {
        Map<Integer, Integer> daysOpen = bugOpenDuration.get( assignee );
        if ( daysOpen == null )
        {
            daysOpen = new HashMap<Integer, Integer>();
            bugOpenDuration.put( assignee, daysOpen );
        }
        
        Integer openDays = daysOpen.get( bugID );
        if ( openDays == null ) openDays = 0;
        
        daysOpen.put( bugID, openDays + 1 );
    }

    private void markBugClosed(User assignee, int bugID)
    {
        Collection<Integer> closedBugs = currentlyClosedBugs.get( assignee );
        if ( closedBugs == null )
        {
            closedBugs = new HashSet<Integer>();
            currentlyClosedBugs.put( assignee, closedBugs );
        }
        
        closedBugs.add( bugID );
    }

    @Override
    protected TimedIntegerReport createNewReport(User assignedTo)
    {
        final TimedIntegerReport result = new TimedIntegerReport();
        
        result.setGroup( GeneratorsStrings.TEXT_OPEN_BUGS_AGE );
        result.setValueName( GeneratorsStrings.TEXT_NO_OF_DAYS );
        
        return result;
    }

    
}